package com.irdstudio.efp.flow.api.rest;

import com.irdstudio.basic.framework.core.constant.ApplicationConstance;
import com.irdstudio.basic.framework.core.constant.ResponseData;
import com.irdstudio.basic.framework.core.util.TimeUtil;
import com.irdstudio.basic.framework.core.vo.EngineHttpRequestVO;
import com.irdstudio.basic.framework.web.util.HttpClientUtil;
import com.irdstudio.basic.sequence.service.facade.SequenceService;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.flow.common.constance.FlowConstance;
import com.irdstudio.efp.flow.executor.util.AbstractController;
import com.irdstudio.efp.flow.service.FlowCommonService;
import com.irdstudio.efp.flow.service.FlowRepulseUtil;
import com.irdstudio.efp.flow.service.facade.FlowUrlConfigService;
import com.irdstudio.efp.riskm.common.RiskColltConstant;
import com.irdstudio.efp.riskm.service.facade.MonReliefAppService;
import com.irdstudio.efp.riskm.service.vo.MonReliefAppVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * 息费减免申请
 */
@RestController
@RequestMapping("/api")
public class MonReliefFlowApprController extends AbstractController {
	
	@Autowired
	@Qualifier("monReliefAppService")
	private MonReliefAppService monReliefAppService;

	@Autowired
	@Qualifier("dbSeqService")
	private SequenceService sequenceService;

	@Autowired
	@Qualifier("flowUrlConfigService")
	private FlowUrlConfigService flowUrlConfigService;

	@Autowired
	private FlowCommonService flowCommonService;

	@Autowired
	@Qualifier("flowRepulseUtil")
	private FlowRepulseUtil flowRepulseUtil;


	/**
	 * 新增数据
	 * @param inMonReliefAppVo
	 * @return
	 */
	@RequestMapping(value="/mon/relief/app", method=RequestMethod.POST)
	public @ResponseBody
    ResponseData<Integer> insertMonReliefApp(@RequestBody MonReliefAppVO inMonReliefAppVo) {
		int outputVo = 0;
		setUserInfoToVO(inMonReliefAppVo);
		try {
			if(Objects.isNull(inMonReliefAppVo.getReliefLmt()) || inMonReliefAppVo.getReliefLmt().intValue() == 0){
				throw new Exception("减免金额填写错误，请核查！");
			}
			//String reliefAppNo = getReliefAppNo();
			//inMonReliefAppVo.setReliefAppNo(reliefAppNo);
			inMonReliefAppVo.setApproveStatus(ConsoleConstant.APRV_STATUS_01);
			inMonReliefAppVo.setCreateUser(inMonReliefAppVo.getLoginUserId());
			inMonReliefAppVo.setCreateUserOrg(inMonReliefAppVo.getLoginUserOrgCode());
			inMonReliefAppVo.setCreateTime(TimeUtil.getCurrentDateTime());
			inMonReliefAppVo.setReliefStatus(RiskColltConstant.RELIEF_STS_01);
			outputVo = monReliefAppService.insertMonReliefApp(inMonReliefAppVo);

			if(outputVo == 1){
				return submitReliefAppr(inMonReliefAppVo, outputVo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseData.create(-1, ApplicationConstance.FAILURE, e.getMessage(), false);
		}
		return getResponseData(outputVo);
		
	}

	/**
	 * 根据主键更新信息
	 *
	 * @param vo
	 * @return
	 */
	@RequestMapping(value = "/mon/relief/app", method = RequestMethod.PUT)
	public @ResponseBody ResponseData<Integer> updateByPk(@RequestBody MonReliefAppVO vo) {
		int outputVo = 0;
		setUserInfoToVO(vo);
		try {
			if(Objects.isNull(vo.getReliefLmt()) || vo.getReliefLmt().intValue() == 0){
				throw new Exception("减免金额填写错误，请核查！");
			}
			vo.setLastChgUsr(vo.getLoginUserId());
			outputVo = monReliefAppService.updateByPk(vo);
			if(outputVo > 0){
				return submitReliefAppr(vo, outputVo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseData.create(-1, ApplicationConstance.FAILURE, e.getMessage(), false);
		}
		return getResponseData(outputVo);

	}

	/**
	 * 获取息费减免申请流水号
	 * @return
	 * @throws Exception
	 */
	private String getReliefAppNo() throws Exception {
		String result = null;
		try {
			result = sequenceService.getSequence("RELIEF_APP_NO", null, null);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("生成减免申请流水号失败，原因:"+e.getMessage());
		}
		return result;
	}

	private ResponseData<Integer> submitReliefAppr(MonReliefAppVO monReliefAppVO, int outputVo) {
		logger.info("发起息费减免申请流程开始，信息为:" + monReliefAppVO.toString());
		int reliefLmt = monReliefAppVO.getReliefLmt().intValue();
		String flowId = "";
		String eventId = "";
		if(reliefLmt < 2000){
			flowId = "FW20191104000000006";
			eventId = FlowConstance.M1_RELIEF_ENTER;
		}else if(reliefLmt >= 2000 &&  reliefLmt < 3000){
			flowId = "FW20191202000000001";
			eventId = FlowConstance.M2_RELIEF_ENTER;
		}else if(reliefLmt >= 3000){
			flowId = "FW20191204000000002";
			eventId = FlowConstance.M3_RELIEF_ENTER;
		}else{
		}
		EngineHttpRequestVO eVo = new EngineHttpRequestVO();
		eVo.setBizLagelOrgCode(monReliefAppVO.getLoginUserOrgCode());
		eVo.setE_bizSerno(monReliefAppVO.getReliefAppNo());
		eVo.setFlowId(flowId);
		//业务事件标识
		eVo.setEventId(eventId);
		eVo.setG_bizSerno(monReliefAppVO.getReliefAppNo());
		eVo.setBizLagelOrgCode(monReliefAppVO.getLoginUserOrgCode());
		eVo.setData(monReliefAppVO);
		try {
			//判断流程配置岗位是否有效
			if (!flowCommonService.dutyFlowCheck(eventId, flowId)){
				throw new Exception("发起息费减免申请流程失败!原因: 流程岗位已失效");
			}
			// 清除打回信息
			if(ConsoleConstant.APRV_STATUS_05.equals(monReliefAppVO.getApproveStatus())){
				flowRepulseUtil.cleanRepulseAllInfo(monReliefAppVO.getReliefAppNo());
			}
			HttpClientUtil.callFlowEngine(flowUrlConfigService.getRestfulSyncStartEventUrl(), eVo, String.class);
			monReliefAppVO.setApproveStatus(ConsoleConstant.APRV_STATUS_02);
			monReliefAppVO.setReliefStatus(RiskColltConstant.RELIEF_STS_02);
			monReliefAppVO.setLastChgUsr(monReliefAppVO.getLoginUserId());
			int updNum = monReliefAppService.updateByPk(monReliefAppVO);
			if(updNum != 1){
				logger.error("通过息费减免申请流水号:"+ monReliefAppVO.getReliefAppNo() + "，更新审批状态为审批中失败！");
			}
		} catch (Exception e) {
			/**
			 * @date 2020/01/02
			 * 息费减免有修改功能，流程发起失败的申请数据就不必删除，用户可解决流程发起失败问题，重新发起
			 */
			//monReliefAppService.deleteByPk(monReliefAppVO);
			e.printStackTrace();
			outputVo = -1;
			return ResponseData.create(outputVo, ApplicationConstance.FAILURE, "发起息费减免申请审批流程失败!原因:" + e.getMessage(), false);
		}
		return getResponseData(1);
	}


}
